/// CreateTime 2020/7/6 9:49
/// CreateUser chen 
/// ProjectName flutter_elf
import 'package:flutter_elf/config/component_index.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
typedef Widget GetItem(m);
typedef Future<T> FutureData<T>(int page);
class BaseCommonRefreshPage<W extends Widget,T,M>  extends StatefulWidget{
  final Widget top;
  final String title;
  final int limit;
  final GetItem getItem;
  final FutureData<T> futureData;


  BaseCommonRefreshPage({this.top, this.title, this.limit,this.getItem, this.futureData});
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return BaseCommonRefreshPageState<T,M,W>();
  }
}

class BaseCommonRefreshPageState<T,M,W extends Widget> extends State<BaseCommonRefreshPage>{
  int page ;
  List<M> data = [];
  RefreshController _refreshController;
  ScrollController _scrollController;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _scrollController = new ScrollController();
    _refreshController = RefreshController();
    initData();
  }

  initData()async{
    page = 0;
    data.clear();
    dynamic response = await widget.futureData(page);
    if (response?.data?.vData?.isNotEmpty ?? false) {
      page++;
      data.addAll(response?.data?.vData);
      setState(() {
        if (response?.data?.vData?.length == 0) {
          _refreshController.refreshCompleted();
        }
      });
    }
  }

  Future<void> _onRefresh()async{
    data.clear();
    dynamic response = await widget.futureData(page);
    if (response?.data?.vData?.isNotEmpty ?? false) {
      page++;
      data.addAll(response?.data?.vData);
      setState(() {
        if (response?.data?.vData?.length == 0) {
          _refreshController.refreshCompleted();
        }
      });
    }
  }

   _onLoading()async{
    dynamic response = await widget.futureData(page);
    if (response?.data?.vData?.isNotEmpty ?? false) {
      page++;
      data.addAll(response?.data?.vData);
      setState(() {
        globalPrint('一共多少条数据=== 》 ' + data.length.toString());
        if (response?.data?.vData?.length == 0) {
          _refreshController.refreshCompleted();
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      body: SmartRefresher(
          child: ListView.builder(
            itemBuilder: (c, i) => widget.getItem(data[i]),
            itemExtent: 100.0,
            controller: _scrollController,
            itemCount: data.length,
          ),
          onRefresh: _onRefresh,
          onLoading: () {
            _onLoading();
          },
          enablePullDown: true,
          enablePullUp: true,
          controller: _refreshController),
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _scrollController?.dispose();
    _refreshController?.dispose();
    super.dispose();
  }

}